package com.shadow.bus.main.work;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.shadow.bus.adapter.MultipleTypeAdapter;
import com.shadow.bus.config.ItemFiled;
import com.shadow.bus.config.ItemType;
import com.shadow.bus.config.NetState;
import com.shadow.bus.config.PersistData;
import com.shadow.bus.config.ServiceUrl;
import com.shadow.bus.config.SpKey;
import com.shadow.bus.entity.OperationEntity;
import com.shadow.bus.entity.PostRepairInfo;
import com.shadow.bus.entity.ProcessEntity;
import com.shadow.bus.entity.RepairEntity;
import com.shadow.bus.entity.TroubleEntity;
import com.shadow.bus.entity.TroubleOperationEntity;
import com.shadow.bus.event.RefreshWorkEvent;
import com.shadow.bus.event.SearchPersonEvent;
import com.shadow.bus.event.SearchResultEvent;
import com.shadow.bus.ic.IcManager;
import com.shadow.bus.ic.OpenIcEvent;
import com.shadow.bus.main.alarm.AlarmDelegate;
import com.shadow.bus.main.complete.CompleteWorkDelegate;
import com.shadow.bus.main.history.HistoryDelegate;
import com.shadow.bus.main.search.SearchDelegate;
import com.shadow.bus.main.search_code.NameFragment;
import com.shadow.bus.main.setting.NFCDialogActivity;
import com.shadow.bus.tools.AESUtils;
import com.shadow.bus.tools.SPUtils;
import com.shadow.bus.tools.UsbUtil;
import com.tepth.shadow.ui.dialog.sweet.DialogDelegate;
import com.tepth.shadow.ui.dialog.sweet.SweetAlertDialogDelegate;
import com.tepth.shadow.ui.recycler.BaseDecoration;
import com.tepth.shadow.ui.recycler.MultipleItemEntity;
import com.zhangyu.shadow.core.delegate.RxShadowDelegate;
import com.zhangyu.shadow.core.net.callback.IError;
import com.zhangyu.shadow.core.net.callback.ISuccess;
import com.zhangyu.shadow.core.net.rx.RxRestClient;
import com.zhangyu.shadow.core.util.storage.ShadowPreference;
import com.zhangyu.shadow.core.util.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import busfix.tepth.com.shadow_bus.R;
import busfix.tepth.com.shadow_bus.R2;
import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author zhangyu
 * @date 2018/7/4
 */

public class WorkDelegate extends RxShadowDelegate {
    private static final String BUS_CODE = "busCode";
    private static final String BUS_ID = "busId";

    public static WorkDelegate newInstance(String code, long id) {
        Bundle args = new Bundle();
        args.putString(BUS_CODE, code);
        args.putLong(BUS_ID, id);
        WorkDelegate fragment = new WorkDelegate();
        fragment.setArguments(args);
        return fragment;
    }

    @BindView(R2.id.toolbar)
    Toolbar mToolbar;
    @BindView(R2.id.recycler_view_trouble)
    RecyclerView mRecyclerViewTrouble;
    private MultipleTypeAdapter mTypeAdapter;
    private String mBusCode;
    private long mBusId;
    private List<TroubleOperationEntity> mSelectList = new ArrayList<>();
    private List<TroubleEntity> mTroubleEntities;
    private DialogDelegate mDialogDelegate;
    private PunchState mPunchState = PunchState.passCheck;
    private MultipleItemEntity mCurrentCancelTroubleOperation;
    private int mCurrentCancelPosition;

    private enum PunchState {
        cancel,
        work,
        passCheck,
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle != null) {
            mBusCode = bundle.getString(BUS_CODE);
            mBusId = bundle.getLong(BUS_ID);
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_work;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        onRefresh(null);
    }

    private void requestData() {
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.REPAIR_INFO)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("id", mBusId)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        new WorkDataMultipleConverter().convert(response, new WorkDataMultipleConverter.OnConverterListener() {
                            @Override
                            public void onConverterAllData(ArrayList<MultipleItemEntity> list) {
                                try {
                                    mTypeAdapter.setNewData(list);
                                    mDialogDelegate.clearDialog();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }

                            }

                            @Override
                            public void onConverterTroubles(List<TroubleEntity> troubleEntities) {
                                mTroubleEntities = troubleEntities;
                            }

                            @Override
                            public void onConverterRepairInfo(RepairEntity repairEntity) {
                            }

                            @Override
                            public void onConverterError(String msg) {
                                if (mDialogDelegate != null) {
                                    mDialogDelegate.stopProgressWithFailed("请求失败", msg);
                                }
                            }
                        });
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {

                    }
                })
                .build()
                .get());
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {
        EventBus.getDefault().register(this);
        mToolbar.inflateMenu(R.menu.history);
        mToolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                pop();
            }
        });
        mToolbar.setTitle("车辆编号:" + mBusCode + "维修信息");
        mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                int i = item.getItemId();
                if (i == R.id.menu_history) {
                    start(HistoryDelegate.newInstance(mBusCode));
                }
                return true;
            }
        });
//        FlexboxLayoutManager layoutManager = new FlexboxLayoutManager(getContext());
//        layoutManager.setFlexWrap(FlexWrap.WRAP);
//        layoutManager.setAlignItems(AlignItems.STRETCH);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mRecyclerViewTrouble.setLayoutManager(layoutManager);
        mRecyclerViewTrouble.addItemDecoration(BaseDecoration.create(getContext().getResources()
                .getColor(R.color.color_white), 2));
        mRecyclerViewTrouble.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                MultipleItemEntity itemEntity = (MultipleItemEntity) adapter.getItem(position);
                List<MultipleItemEntity> list = adapter.getData();
                int i = view.getId();
                if (i == R.id.tv_add) {
                    if (itemEntity != null) {
                        TroubleEntity troubleEntity = itemEntity.getField(ItemFiled.ITEM_OBJ);
                        showSelectOperatorDialog(troubleEntity, position);
                    }

                } else if (i == R.id.iv_delete) {
                    if (itemEntity != null) {
                        TroubleOperationEntity operationEntity = itemEntity.getField(ItemFiled.ITEM_OBJ);
                        list.remove(position);
                        adapter.notifyItemRemoved(position);
                        mSelectList.remove(operationEntity);
                    }
                } else if (i == R.id.tv_add_trouble) {
                    TroubleOperationEntity entity = null;
                    if (itemEntity != null) {
                        entity = itemEntity.getField(ItemFiled.ITEM_OBJ);
                    }
                    showDialogAddOtherTrouble(entity, position);
                } else if (i == R.id.tv_cancel) {
                    if (itemEntity != null) {
                        mCurrentCancelTroubleOperation = itemEntity;
                        mCurrentCancelPosition = position;
                        mPunchState = PunchState.cancel;
                        if (ShadowPreference.getAppFlag(SpKey.KEY_CARD_WAY)) {
                            if (UsbUtil.hasUsbDevice(getActivity())) {
                                mDialogDelegate.showProgressDialog(true, "正在打开设备...");
                                mDialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                                    @Override
                                    public void onDismiss(DialogInterface dialog) {
                                        IcManager.getInstance().leisureDevice();
                                    }
                                });
                                IcManager.getInstance().openDevice();
                            } else {
                                startActivityForResult(new Intent(getActivity(), NFCDialogActivity.class),
                                        200);
                            }
                        } else {
                            NameFragment.newInstance().show(getChildFragmentManager(), "fragment_name");
                        }
                    }
                }

            }
        });
        mDialogDelegate = new SweetAlertDialogDelegate(getContext());
        mTypeAdapter = new MultipleTypeAdapter(getContext(), null, mSelectList);
        mRecyclerViewTrouble.setAdapter(mTypeAdapter);
    }

    private void showSelectOperatorDialog(final TroubleEntity troubleEntity, final int position) {
        new SelectOperatorDialog(getActivity(), troubleEntity, new SelectOperatorDialog.OnOperatorListener() {
            @Override
            public void onAddProcessOperator(ProcessEntity processEntity) {
                TroubleOperationEntity entity = new TroubleOperationEntity();
                entity.setId(0);
                entity.setTroubleTypeName(troubleEntity.getName());
                entity.setTroubleTypeId(troubleEntity.getTroubleTypeId());
                entity.setTroubleId(troubleEntity.getId());
                if (troubleEntity.getClassification() != null) {
                    entity.setClassificationId(troubleEntity.getClassification().getId());
                    entity.setClassificationName(troubleEntity.getClassification().getName());
                }
                entity.setOperation(processEntity.getOperation());
                entity.setAccessory(processEntity.getAccessory());
                entity.setComponent(processEntity.getComponent());
                entity.setUseCount(1);
                ArrayList<TroubleOperationEntity> troubleOperationEntities = troubleEntity.getListContent();
                if (troubleOperationEntities == null) {
                    troubleOperationEntities = new ArrayList<>();
                    troubleEntity.setListContent(troubleOperationEntities);
                }
                troubleOperationEntities.add(entity);
                EventBus.getDefault().post(new SearchResultEvent(entity, position, troubleEntity));
            }

            @Override
            public void onAlarm() {
                start(AlarmDelegate.newInstance(mBusId, mBusCode));
            }

            @Override
            public void onAddOtherOperator() {
                if (PersistData.getInstance().getOperationEntities() == null) {
                    mDialogDelegate.showProgressDialog(false, "正在加载...");
                    if (!NetState.IS_NET_CONNECT) {
                        mDialogDelegate.stopProgressWithFailed("没有网络", "请检查网络！");
                    } else {
                        mDisposables.add(RxRestClient.builder()
                                .url(ServiceUrl.OPERATOR_LIST)
                                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                                .success(new ISuccess() {
                                    @Override
                                    public void onSuccess(String response) {
                                        mDialogDelegate.clearDialog();
                                        PersistData.getInstance().setOperationEntities(new OperatorDataConverter()
                                                .converter(response));
                                        new ChooseOperatorDialog(getActivity(), new ChooseOperatorDialog.OnOperationChooseListener() {
                                            @Override
                                            public void onChoose(OperationEntity operationEntity) {
                                                start(SearchDelegate.newInstance(operationEntity, troubleEntity, position));
                                            }
                                        }).show();
                                    }
                                })
                                .error(new IError() {
                                    @Override
                                    public void onError(int code, String msg) {
                                        mDialogDelegate.stopProgressWithFailed("加载失败", msg);
                                    }
                                })
                                .build()
                                .get());
                    }
                } else {
                    new ChooseOperatorDialog(getActivity(), new ChooseOperatorDialog.OnOperationChooseListener() {
                        @Override
                        public void onChoose(OperationEntity operationEntity) {
                            start(SearchDelegate.newInstance(operationEntity, troubleEntity, position));
                        }
                    }).show();
                }
            }


        }).show();
    }

    private void showDialogAddOtherTrouble(final TroubleOperationEntity troubleBean, final int position) {
        new AddOtherTroubleDialog(_mActivity, troubleBean, new AddOtherTroubleDialog.OnAddOtherTroubleListener() {
            @Override
            public void onAdd(List<TroubleEntity> remarkTroubles) {
                ArrayList<TroubleEntity> list = troubleBean.getChildren();
                if (list == null) {
                    list = new ArrayList<>();
                    troubleBean.setChildren(list);
                }
                list.addAll(remarkTroubles);
                mTypeAdapter.notifyItemChanged(position);
            }
        }, mTroubleEntities).show();
    }

    @Subscribe
    public void onSearchResult(SearchResultEvent event) {
        //搜索部件的添加
        MultipleItemEntity multipleItemEntity = mTypeAdapter.getItem(event.mPosition);
        if (multipleItemEntity != null) {
            TroubleEntity troubleEntity = multipleItemEntity.getField(ItemFiled.ITEM_OBJ);
            ArrayList<TroubleOperationEntity> operationEntities = troubleEntity.getListContent();
            if (operationEntities == null) {
                operationEntities = new ArrayList<>();
                troubleEntity.setListContent(operationEntities);
            }
            operationEntities.add(event.mTroubleOperationEntity);
        }
        mTypeAdapter.addData(event.mPosition + 1, MultipleItemEntity.builder().setItemType(ItemType.TYPE_ITEM_TROUBLE_OPERATOR_WORK)
                .setField(ItemFiled.ITEM_OBJ, event.mTroubleOperationEntity)
                .setField(ItemFiled.ITEM_TROUBLE_ID, event.mTroubleEntity.getId())
                .setField(ItemFiled.ITEM_TROUBLE_NAME, event.mTroubleEntity.getName())
                .build());
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public boolean onBackPressedSupport() {
        pop();
        return true;
    }

    public static final int MIN_CLICK_DELAY_TIME = 1000;
    private long mLastClickTime = 0;

    @OnClick(R2.id.btn_work)
    public void onWorkPunch() {
        //防止多次点击
        long currentTime = Calendar.getInstance().getTimeInMillis();
        if (currentTime - mLastClickTime > MIN_CLICK_DELAY_TIME) {
            mLastClickTime = currentTime;
            if (mSelectList.size() > 0) {
                mPunchState = PunchState.work;
                if (ShadowPreference.getAppFlag(SpKey.KEY_CARD_WAY)) {
                    if (UsbUtil.hasUsbDevice(getActivity())) {
                        mDialogDelegate.showProgressDialog(true, "正在打开设备...");
                        mDialogDelegate.getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                                IcManager.getInstance().leisureDevice();
                            }
                        });
                        IcManager.getInstance().openDevice();
                    } else {
                        ToastUtils.showToast(getContext(), "未检测到打卡器");
                    }
                } else {
                    NameFragment.newInstance().show(getChildFragmentManager(), "fragment_name");
                }
            } else {
                ToastUtils.showToast(getActivity(), "请选择操作项!");
            }
        } else {
            ToastUtils.showToast(getActivity(), "点得太快啦!");
        }
    }

    @OnClick(R2.id.btn_complete)
    public void onComplete() {
        start(CompleteWorkDelegate.newInstance(mBusCode, mBusId));
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null && data.hasExtra("BarCodeContents")) {
            byte[] displayContents = data.getByteArrayExtra("BarCodeContents");
            String[] result = analysisData(new String(displayContents));
            if (result != null) {
                switch (mPunchState) {
                    case work:
                        workCard(result);
                        break;
                    case cancel:
                        cancelWork(result);
                        break;
                }
            }
        }
    }

    @Subscribe()
    public void onICEvent(final OpenIcEvent event) {
        //接收了该事件就拦截掉 不会继续往优先级小于priority的地方传递
        if (!event.isSuccess) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialogDelegate != null) {
                        mDialogDelegate.changeText(event.mTitle, (String) event.mObject);
                    }
                }
            });
        } else {
            byte[] displayContents = (byte[]) event.mObject;
            String[] result = analysisData(new String(displayContents));
            if (result != null) {
                //将打卡人存入缓存
                HashMap<String, String> hashMap = (HashMap<String, String>) SPUtils.getObject(getContext(), SpKey.KEY_HISTORY_USER);
                if (hashMap == null) {
                    hashMap = new HashMap<>();
                }
                hashMap.put(result[0], result[1]);
                SPUtils.putObject(getContext(), SpKey.KEY_HISTORY_USER, hashMap);
                switch (mPunchState) {
                    case work:
                        workCard(result);
                        break;
                    case cancel:
                        cancelWork(result);
                        break;
                }
            }
        }
    }

    @Subscribe()
    public void onSearchPersonEvent(SearchPersonEvent event) {
        String[] result = new String[2];
        result[0] = event.code;
        result[1] = event.name;
        switch (mPunchState) {
            case work:
                workCard(result);
                break;
            case cancel:
                cancelWork(result);
                break;
        }
    }

    private String[] analysisData(String data) {
        String result;
        try {
            result = AESUtils.code_desEncrypt(data);
            if (result.isEmpty()) {
                ToastUtils.showToast(getContext(), "AES解码失败");
                return null;
            }
            String[] results = result.split("_");
            if (result.length() < 2) {
                ToastUtils.showToast(getContext(), "数组长度小于2");
                return null;
            }
            return results;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 作业打卡
     *
     * @param result
     */
    private void workCard(String[] result) {

        String personNumber = result[0];
        String personName = result[1].trim();
        PostRepairInfo repairInfo = new WorkDataMultipleConverter().convert(mSelectList,
                (int) mBusId, personNumber, personName);
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (mDialogDelegate != null) {
                    if (mDialogDelegate.getDialog().isShowing()) {
                        mDialogDelegate.changeText("读取成功!", "正在提交...");
                    } else {
                        mDialogDelegate.showProgressDialog(true, "正在提交...");
                    }
                }
            }
        });
        String info = JSON.toJSONString(repairInfo);
        Log.e("workCard", info);
        mDisposables.add(RxRestClient.builder()
                .url(ServiceUrl.START_REPAIR)
                .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                .params("repairInfo", info)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        mDialogDelegate.changeText("打卡成功!", "正在刷新...");
                        mSelectList.clear();
                        requestData();
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        mDialogDelegate.stopProgressWithFailed("提交失败", msg);
                    }
                })
                .build()
                .post());
    }

    /**
     * 取消打卡
     */
    private void cancelWork(String[] result) {
        final TroubleOperationEntity operationEntity = mCurrentCancelTroubleOperation.
                getField(ItemFiled.ITEM_OBJ);
        String number = result[0];
        if (!operationEntity.getWorkPerson().getCode().equals(number)) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialogDelegate != null) {
                        if (mDialogDelegate.getDialog().isShowing()) {
                            mDialogDelegate.stopProgressWithFailed("提交失败", "非本人不能取消打卡");
                        } else {
                            ToastUtils.showToast(getContext(), "非本人不能取消打卡");
                        }
                    }
                }
            });
        } else {
            TroubleEntity trouble = new TroubleEntity();
            ArrayList<TroubleOperationEntity> list = new ArrayList<>();
            list.add(operationEntity);
            trouble.setListContent(list);
            String json = JSON.toJSONString(trouble);
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mDialogDelegate != null) {
                        if (mDialogDelegate.getDialog().isShowing()) {
                            mDialogDelegate.changeText("读取成功!", "正在提交...");
                        } else {
                            mDialogDelegate.showProgressDialog(true, "正在提交...");
                        }
                    }
                }
            });
            mDisposables.add(RxRestClient.builder()
                    .url(ServiceUrl.CANCEL_PUNCH_CARD)
                    .params("authKey", ShadowPreference.getCustomAppProfile(SpKey.TOKEN))
                    .params("json", json)
                    .success(new ISuccess() {
                        @Override
                        public void onSuccess(String response) {
                            operationEntity.setWorkPerson(null);
                            operationEntity.setId(0);
                            operationEntity.setChecked(false);
                            MultipleItemEntity itemEntity = MultipleItemEntity
                                    .builder()
                                    .setItemType(ItemType.TYPE_ITEM_TROUBLE_OPERATOR_WORK)
                                    .setField(ItemFiled.ITEM_TROUBLE_ID,
                                            mCurrentCancelTroubleOperation.getField(ItemFiled.ITEM_TROUBLE_ID))
                                    .setField(ItemFiled.ITEM_TROUBLE_NAME,
                                            mCurrentCancelTroubleOperation.getField(ItemFiled.ITEM_TROUBLE_NAME))
                                    .setField(ItemFiled.ITEM_OBJ, operationEntity)
                                    .build();
                            mTypeAdapter.setData(mCurrentCancelPosition, itemEntity);
                            if (mDialogDelegate != null) {
                                mDialogDelegate.clearDialog();
                            }
                        }
                    })
                    .error(new IError() {
                        @Override
                        public void onError(int code, String msg) {
                            if (mDialogDelegate != null) {
                                mDialogDelegate.stopProgressWithFailed("提交失败", msg);
                            }
                        }
                    })
                    .build()
                    .post());
        }
    }

    @Subscribe
    public void onRefresh(RefreshWorkEvent event) {
        mDialogDelegate.showProgressDialog(true, "正在加载...");
        requestData();
    }

}
